package pay

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"web/order/global"
	"web/order/proto"
)

// 处理支付宝的回调请求
func Notify(ctx *gin.Context) {
	// 第三个参数表示是否为开发环境
	client, err := alipay.New(global.ServerConfig.AlipayInfo.AppId, global.ServerConfig.AlipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Error("实例化支付对象失败：", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": "内部错误: 构建请求支付宝的url失败",
		})
		return
	}
	err = client.LoadAliPayPublicKey(global.ServerConfig.AlipayInfo.AliPublicKey)
	if err != nil {
		zap.S().Error("加载支付宝的公钥失败：", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": "内部错误: 加载支付宝的公钥失败",
		})
		return
	}

	noti, err := client.GetTradeNotification(ctx.Request)
	if err != nil {
		zap.S().Error("获取支付回调信息出错：", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{})
		return
	}

	_, err = global.OrderSrvClient.UpdateOrderStatus(context.Background(), &proto.OrderStatus{
		OrderSn: noti.OutTradeNo,
		Status:  string(noti.TradeStatus),
	})
	if err != nil {
		zap.S().Error("更新订单状态出错：", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{})
		return
	}

	// 告知支付宝，已收到回调通知，不必再发送回调通知过来了
	ctx.String(http.StatusOK, "success")
}
